<template>
  <div class="fillcontain">
    <!-- 具体配置 -->
    <div class="content">
      <!-- 左侧树 -->
      <div class="left-tree">
        <div class="tree-filter">
          <el-input
            placeholder="请输入"
            v-model="filterText"
            suffix-icon="el-icon-search">
          </el-input>
        </div>
        <el-tree
          @node-click="closeMenu"
          class="tree-content"
          :data="treeData"
          node-key="_id"
          :props="defaultProps"
          :filter-node-method="filterNode"
          :default-expanded-keys="defaultShowNodes"
          @node-expand="handleNodeExpand"
          @node-collapse="handleNodeCollapse"
          ref="tree">
          <span class="custom-tree-node" slot-scope="{ node, data }" @contextmenu.prevent="openMenu($event,data)">
            <icon-svg v-if="node.level != 2" style="font-size: 18px" iconClass="icon-yuanhuise"></icon-svg>
            <i v-else :class="['expanded',{'el-icon-plus':!node.expanded,'el-icon-minus':node.expanded}]"></i>
            <span :class="['node-ellips','node-label' + data._id,{'node-label':data.level == 3}]" @click="handleNodeClick($event,data,node)">{{ node.label }}</span>
            <span v-if="data.level == 2 && data.children">（{{data.children.length}}）</span>
          </span>
        </el-tree>

        <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextMenu">
          <li @click="addRule(1)" v-if="currentData && currentData.level == 1">添加疾病规则</li>
          <li @click="addRule(2)" v-if="currentData && currentData.level == 2" style="border-bottom: 1px solid #dadce0;margin: 0px;padding-bottom: 8px;">修改</li>
          <li @click="addRule(3)" v-if="currentData && currentData.level == 2">删除</li>
          <li @click="addRule(4)" v-if="currentData && currentData.level == 3">删除</li>
        </ul>
      </div>
      <!-- 右侧配置信息 -->
      <div class="right-main">
        <!-- 操作按钮 -->
        <el-row class="btn-list" v-if="ruleType">
          <el-col :span="24" class="pb15 pt5">
            <el-button
              type="danger"
              size="mini"
              style="margin-left: 10px"
              :disabled='coverFlag'
              plain
              @click="coverVersion()"
              :loading="coverLoading"
              >覆盖原版本
            </el-button>
            <el-button
              type="danger"
              size="mini"
              style="margin-left: 10px"
              plain
              @click="addNewVersion()"
              >保存新版本
            </el-button>
            <el-button
              type="danger"
              size="mini"
              style="margin-left: 10px"
              plain
              @click="importExcel()"
              :loading="importLoading"
              >导出Excel
            </el-button>
            <el-button
              type="danger"
              size="mini"
              style="margin-left: 10px"
              plain
              @click="viewVersion()"
              >查看版本
            </el-button>
          </el-col>
          <p v-if="!coverFlag" class="currentVesion">当前版本号：{{currentVersion}}</p>
        </el-row>
        <!-- 体检风险规则组件 -->
        <physicalRiskRule v-if="ruleType == '1'" ref="physicalRiskRule" :projectCategoryDic="projectCategoryDic" :projectNameDic="projectNameDic" :logicDic="logicDic" @getCoverFlag="getCoverFlag"></physicalRiskRule>
        <!-- 健康风险规则组件 -->
        <healthRiskRule v-else-if="ruleType == '2'" ref="healthRiskRule" :logicDic="logicDic" @getCoverFlag="getCoverFlag"></healthRiskRule>
        <!-- 特殊评分项规则组件 -->
        <specialScoreRule v-else-if="ruleType == '3'" ref="specialScoreRule" :logicDic="logicDic" @getCoverFlag="getCoverFlag"></specialScoreRule>
        <!-- 核保结论规则组件 -->
        <underwriteEvaluationRule v-else-if="ruleType == '4'" ref="underwriteEvaluationRule" :logicDic="logicDic" @getCoverFlag="getCoverFlag"></underwriteEvaluationRule>
      </div>
    </div>

    <!-- 新增疾病规则弹窗 -->
    <el-dialog
      :title="currentData && currentData.level == 1 ? '新增疾病规则' : '编辑疾病规则'"
      :visible.sync="addRuleVisible"
      width="850px"
      :show-close="false"
      :close-on-click-modal="false"
      @close="ruleDialogClose"
      center>
      <el-form v-if="addRuleVisible" :model="diseaseRuleForm" :rules="diseaseRules" ref="ruleForm" label-width="120px" class="search_container">
        <el-row>
          <el-col :span="12">
            <el-form-item label="关联疾病：" prop="diseaseId">
              <el-select v-model="diseaseRuleForm.diseaseId" placeholder="请选择" filterable remote clearable :remote-method="remoteMethod" @visible-change="visibleChange($event)" v-loadMore="loadMore" :disabled="currentData.level == 2">
                <el-option
                  v-for="item in diseaseDic"
                  :key="item.id"
                  :label="item.diseaseName"
                  :value="item.id + ''">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange" style="margin: 10px 65px;">关联规则组</el-checkbox>
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题：" prop="ruleGroup">
              <el-checkbox-group v-model="diseaseRuleForm.ruleGroup" @change="handleCheckedCitiesChange">
                <el-checkbox v-for="item in ruleGroupDic" :label="item.value" :key="item.value" :disabled="currentRuleList.indexOf(item.value) > -1">{{item.label}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="ruleSaveClick">保 存</el-button>
        <el-button @click="addRuleVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 保存新版本弹窗 -->
    <el-dialog
      title="保存新版本"
      :visible.sync="versionVisible"
      width="950px"
      :show-close="false"
      :close-on-click-modal="false"
      @close="versionDialogClose"
      center>
      <el-form v-if="versionVisible" :model="versionForm" :rules="versionRules" ref="versionForm" label-width="120px" class="search_container">
        <el-row>
          <el-col :span="12">
            <el-form-item label="版本名称：" prop="versionName">
              <el-input v-model="versionForm.versionName" placeholder="请输入版本名称" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="版本号：" prop="versionCode">
              <el-input v-model="versionForm.versionCode" placeholder="请输入版本号" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注：">
              <el-input type="textarea" :rows="6" v-model="versionForm.remark" placeholder="请输入备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="versionSaveClick" :loading="saveLoading">保 存</el-button>
        <el-button @click="versionVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 查看版本 -->
    <el-dialog
      title="查看版本"
      :visible.sync="viewVisible"
      width="950px"
      :close-on-click-modal="false"
      center>
      <versionView ref="versionView" :ruleType="ruleType" :diseaseRuleId="diseaseRuleId" @specifiedVersion="specifiedVersion"></versionView>
      <span slot="footer" class="dialog-footer">
        <el-button @click="viewVisible = false">返 回</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 处理树结构
const treeDataHandle = (array, childrenName = 'children') => {
  if (!Array.isArray(array)) return []
  let count = 0
  const recursive = (array,count) => {
    count ++
    return array.map(v => {
      v.level = count
      if(v.diseaseRuleList) v.children = v.diseaseRuleList.length ? v.diseaseRuleList : null

      // 处理树标题
      if(v.diseaseName) {
        v.label = v.diseaseName
        v._id = 100000 + v.id
      }
      if(v.healthTypeName) {
        v.label = v.healthTypeName
        v._id = v.id
      }

      const child = v[childrenName]
      if (child && child.length) recursive(child,count)
      return v
    })
  }
  return recursive(array,count)
};

import physicalRiskRule from "../../../component/physicalRiskRule";
import healthRiskRule from "../../../component/healthRiskRule";
import specialScoreRule from "../../../component/specialScoreRule";
import underwriteEvaluationRule from "../../../component/underwriteEvaluationRule";
import versionView from "../../../component/versionView";

import constant from '@/utils/constant';

import {
  // 体检风险规则
  getDiseaseListApi,
  getRuleConfigMenuApi,
  addRuleConfigMenuApi,
  delRuleConfigMenuApi,
  getProjectCategoryApi,
  getProjectNameApi,
  savePhysicalRiskRuleApi,
  saveNewPhysicalRiskRuleApi,
  importPhysicalRiskRuleApi,
  delPhysicalRiskRuleApi,

  // 健康风险项
  saveHealthRiskRuleApi,
  saveNewHealthRiskRuleApi,
  importHealthRiskRuleApi,
  delHealthRiskRuleApi,

  // 特殊评分项
  saveSpecialScoreRuleApi,
  saveNewSpecialScoreRuleApi,
  importSpecialScoreRuleApi,
  delSpecialScoreRuleApi,

  // 核保评点项
  saveUnderwritingEvaluationRuleApi,
  saveNewUnderwritingEvaluationRuleApi,
  importUnderwritingEvaluationRuleApi,
  delUnderwritingEvaluationRuleApi,

  // 字典
  getNameDictProjectApi,
  getOwnDictProjectApi,
  getPhysicalRiskRuleVersionApi,
  getHealthRiskRuleVersionApi,
  getSpecialScoreRuleVersionApi,
  getUnderwritingEvaluationRuleVersionApi

} from "@/api/medicalLibrary/examProjectLibrary";

import { getHqnrInfo } from "@/api/taskCenter/manualEntry";

export default {
  directives: {
    loadMore: {
      // el 可以获取当前dom节点， binding一个对象(具体可以自行打印观察)，vnode第三个参数为虚拟节点
      bind (el, binding) {
        // 获取element，定义scroll
        const selectDom = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
         // 添加滚动事件
	      selectDom.addEventListener('scroll', function () {
	      // scrollHeight所有数据占据面的一个高度,，scrollTop滚动条滚走的区域高度，clientHeight可视区域面积高度
          const height = selectDom.scrollHeight - selectDom.scrollTop - 5 <= selectDom.clientHeight;
          if (height) {
            binding.value();
          }
        });
      }
    }
  },
  components: {
		physicalRiskRule,
    healthRiskRule,
    specialScoreRule,
    underwriteEvaluationRule,
    versionView
	},
    data() {
      return {
        diseaseDic: [],  //疾病下拉列表
        ruleGroupDic: [], //规则组枚举值
        projectCategoryDic: [],  //体检项对象.项目大类
        projectNameDic: [], //体检项对象.项目名称
        logicDic: [], //逻辑符
        filterText: '',
        treeData: [],
        defaultShowNodes: [99999], // 这里存放要默认展开的节点 id
        currentDiseaseRuleId: '', //当前默认点击的节点id
        defaultProps: {
          children: 'children',
          label: 'label'
        },

        // 点击哪个疾病下的规则
        ruleType: '', //点击疾病下的规则类型 1、体检风险项规则、2健康风险项规则、3特殊评分规则、4核保结论规则
        diseaseRuleId: '',  //点击的规则类型id
        diseaseName: '',  //疾病名称
        versionId: '', // 当前请求的版本号
        currentVersion: '',
        coverFlag: false, //是否禁用覆盖原版本的按钮
        // 右键目录
        visible: false,
        currentData: null, //当前点击的节点信息
        currentRuleList: [],
        top: 0,
        left: 0,

        // 点击保存、导入按钮时显示加载中
        importLoading: false,
        coverLoading: false,
        saveLoading: false,

        // 新增疾病规则弹窗
        diseaseRuleForm: {
          diseaseId: '',
          ruleGroup: []
        },
        diseaseRules: {
          diseaseId: [{ required: true, message: '请选择关联疾病',trigger: 'change'}],
          ruleGroup: [{ type: 'array',  required: true, message: '请选择关联规则组',trigger: 'change'}]
        },
        addRuleVisible: false,
        checkAll: false,
        isIndeterminate: true,
        // select框分页
        page: {
          pageNum: 1,
          pageSize: 100,
          parameter: ''
        },
        moreFlag: true,

        // 保存新版本弹窗
        versionForm: {
          versionName: '',
          versionCode: '',
          remark: ''
        },
        versionRules: {
          versionName: [{ required: true, message: '请输入版本名称',trigger: 'blur'}],
          versionCode: [{ required: true, message: '请输入版本号',trigger: 'blur'}]
        },
        versionVisible: false,

        // 查看版本的弹窗
        viewVisible: false
      };
    },
    created(){
      // 查询左侧规则配置树
      this.getRuleConfigTree()
      // 查询体检项对象.项目大类、项目名称、测量结果的列表数据
      this.getPhysicalDic()
      // 获取逻辑符的下拉值
      this.getNameDictProject()
    },
    methods: {
      filterNode(value, data, node) {
        let parentNode = node.parent // 父级node
        let labels = [node.label] // 当前node的名字
        let level = 1 // 层级
        while (level < node.level) {
            labels = [...labels, parentNode.label] // 当前node名字，父级node的名字
            parentNode = parentNode.parent
            level++
        }
        return labels.some(d => d.indexOf(value) !== -1)
      },
      // 查询逻辑符
      getNameDictProject(){
        getOwnDictProjectApi({code: 'ruleType'}).then(res => {
					if (res.resultCode == constant.SUCCESS) {
						this.ruleGroupDic = res.data || []
            this.ruleGroupDic.forEach(item=>{
              item.value = item.remark
              item.label = item.dictValue
            })
					}
				})
        getNameDictProjectApi({name: '逻辑符'}).then(res => {
					if (res.resultCode == constant.SUCCESS) {
						this.logicDic = res.data
					}
				})
      },
      // 查询左侧规则配置树
      getRuleConfigTree(){
        let newTree = [
          {
            label: '智能核保规则',
            _id: 99999
          }
        ]
        this.$store.dispatch('loading/CHANGE_LOADING',true)
        getRuleConfigMenuApi({}).then(res => {
					this.$store.dispatch('loading/CHANGE_LOADING',false)
					if (res.resultCode == constant.SUCCESS) {
						newTree[0].children = res.data
					}
          this.treeData = newTree
          treeDataHandle(this.treeData)
          setTimeout(()=>{
            let className = '.node-label' + this.currentDiseaseRuleId
            if(this.currentDiseaseRuleId && document.querySelector(className)) document.querySelector(className).click()
            else this.ruleType = ''
          },0)
				}).catch(err => {
					this.$store.dispatch('loading/CHANGE_LOADING',false);
				});
      },
      // 树节点展开
      handleNodeExpand (data) {
      	// 保存当前展开的节点
      	let flag = false
      	this.defaultShowNodes.some(item => {
      		if (item === data._id) { // 判断当前节点是否存在， 存在不做处理
      			flag = true
      			return true
      		}
      	})
      	if (!flag) { // 不存在则存到数组里
      		this.defaultShowNodes.push(data._id)
      	}
      },
      // 树节点关闭
      handleNodeCollapse (data) {
      	this.defaultShowNodes.some((item, i) => {
      		if (item === data._id) {
      			// 删除关闭节点
      			this.defaultShowNodes.length = i
      		}
      	})
      },
      visibleChange(flag){
        console.log(flag);
        this.page.pageNum = 1
        this.page.parameter = ''
        if(flag) this.getDiseaseList()
      },
      // 查询疾病下拉列表
      getDiseaseList(){
        let params = {
          pageNum: this.page.pageNum, 
          pageSize: this.page.pageSize,
	        parameter: this.page.parameter
        }
        getHqnrInfo(params).then(res => {
          if (res.resultCode == constant.SUCCESS) {
            this.moreFlag = true
            let transferData = this.diseaseDic
		  	    if(this.page.pageNum == 1) transferData = []
            if(!res.data.list || !res.data.list.length) this.moreFlag = false
		  	    res.data.list.forEach(item => {
		  	    	let obj = {
		  	    		id: item.childCode,
		  	    		diseaseName: item.childName
		  	    	}
		  	    	transferData.push(obj);
            })
            if(!this.page.parameter && this.currentData && this.currentData.diseaseId) {
              let ids = transferData.map(mItem=>mItem.id + '')
              if(ids.indexOf(this.currentData.diseaseId + '') == -1) {
                transferData.push({
                  id: this.currentData.diseaseId,
                  diseaseName: this.currentData.diseaseName
                });
              }
            }
            this.diseaseDic = transferData
          }
        })
      },
      // 查询体检项对象.项目大类、项目名称、测量结果的列表数据
      getPhysicalDic(){
        // 项目大类
        getProjectCategoryApi({}).then(res => {
					if (res.resultCode == constant.SUCCESS) {
						this.projectCategoryDic = res.data
					}
				})
        // 项目名称
        getProjectNameApi({}).then(res => {
					if (res.resultCode == constant.SUCCESS) {
						this.projectNameDic = res.data
					}
				})
      },
      // 获取各类型规则的具体列表信息
      getRuleTypeList(diseaseRuleId = this.diseaseRuleId,version = ''){
        this.versionId = version
        let refName = this.ruleType == '1' ? 'physicalRiskRule' : this.ruleType == '2' ? 'healthRiskRule' : this.ruleType == '3' ? 'specialScoreRule' : 'underwriteEvaluationRule'
        setTimeout(()=>{
          this.$refs[refName].getRiskRule(diseaseRuleId,version)
        },0)
      },
      // 获取版本号
      getCoverFlag(coverFlag,ruleGroupVersionId){
        this.coverFlag = coverFlag
        if(!coverFlag) this.getDataList(ruleGroupVersionId)
      },
      // 获取所有版本信息
      getDataList(ruleGroupVersionId){
        let api = this.ruleType == '1' ? getPhysicalRiskRuleVersionApi : this.ruleType == '2' ? getHealthRiskRuleVersionApi : 
                  this.ruleType == '3' ? getSpecialScoreRuleVersionApi : getUnderwritingEvaluationRuleVersionApi
        api({diseaseRuleId: this.diseaseRuleId}).then(res => {
		  		if (res.resultCode == constant.SUCCESS) {
            this.currentVersion = res.data.filter(fItem=>fItem.id == ruleGroupVersionId)[0].version
		  		}
		  	})
      },
      handleNodeClick($el,data,node){
        if(data.level == 3){
          console.log($el,data,node,'$el,data,node');
          if(this.ruleType == data.ruleType && this.diseaseRuleId == data.id + '') return
          document.querySelectorAll('.node-active').forEach(item=> item.classList.remove('node-active'))
          $el.target.classList.add('node-active')
          this.ruleType = data.ruleType
          this.diseaseRuleId = data.id + ''
          this.diseaseName = node.parent.data.diseaseName
          this.currentDiseaseRuleId = data._id
          this.getRuleTypeList()
        }
      },
      // 点击右键菜单时触发
      addRule(type){
        if(type == 1 || type == 2) {
          this.addRuleVisible = true
          this.currentRuleList = []
          if(type == 2) {
            let ruleTypes = this.currentData.diseaseRuleList.map(item=>item.ruleType)
            this.diseaseRuleForm = {
              diseaseId: this.currentData.diseaseId,
              ruleGroup: ruleTypes
            }
            this.currentRuleList = ruleTypes
          }
        }
        // 删除规则
        else this.deleteNode(type)
        this.closeMenu()
      },
      // 删除节点
      deleteNode(type){
        this.$confirm(type == 3 ? '是否删除此疾病规则?' : '是否删除此规则', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let url = delRuleConfigMenuApi
          if(type == 4){
            if(this.currentData.ruleType == '1') url = delPhysicalRiskRuleApi
            if(this.currentData.ruleType == '2') url = delHealthRiskRuleApi
            if(this.currentData.ruleType == '3') url = delSpecialScoreRuleApi
            if(this.currentData.ruleType == '4') url = delUnderwritingEvaluationRuleApi
          }
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          url(this.currentData.id).then((res) => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
            if(res.resultCode == constant.SUCCESS) {
              this.diseaseRuleId = ''
              this.$message({type: 'success',message: '删除成功!'});
              this.getRuleConfigTree()
            }
          })
          .catch((err) => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
          });
        }).catch(() => {});
      },
      // 右键打开菜单
      openMenu(e,data) {
        this.currentData = data
        // if(data.level != 1) return
        let x = e.clientX;
        let y = e.clientY;
        this.top = y;
        this.left = x;
        // 查询疾病下拉列表
        this.page.parameter = ''
        this.page.pageNum = 1
        this.getDiseaseList()
        this.visible = true;
      },
      // 关闭右键菜单
      closeMenu() {
        this.visible = false;
      },

      // 疾病远程搜索
      remoteMethod(query){
        this.page.parameter = query
        this.page.pageNum = 1
        this.getDiseaseList()
      },
      // 疾病加载
      loadMore(){
        if(!this.moreFlag) return
        this.page.pageNum += 1
        this.getDiseaseList()
      },
      // 新增疾病规则弹窗
      handleCheckAllChange(val) {
        this.diseaseRuleForm.checkedCities = val ? this.ruleGroupDic : [];
        this.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.ruleGroupDic.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.ruleGroupDic.length;
      },
      // 弹窗关闭
      ruleDialogClose(){
        this.diseaseRuleForm = {
          diseaseId: '',
          ruleGroup: []
        }
        this.checkAll = false,
        this.isIndeterminate = true
        this.addRuleVisible = false
      },
      // 疾病规则保存弹窗
      ruleSaveClick(){
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.$store.dispatch('loading/CHANGE_LOADING',true)
            this.diseaseRuleForm.diseaseName = this.diseaseDic.filter(item=>item.id == this.diseaseRuleForm.diseaseId)[0].diseaseName
            if(this.currentData && this.currentData.level == 2) this.diseaseRuleForm.id = this.currentData.id
            /* this.diseaseRuleForm.ruleGroup = this.diseaseRuleForm.ruleGroup.sort((a,b) => a-b) */
            addRuleConfigMenuApi(this.diseaseRuleForm).then(res => {
				    	this.$store.dispatch('loading/CHANGE_LOADING',false)
				    	if (res.resultCode == constant.SUCCESS) {
                this.diseaseRuleId = ''
                this.$message.success(this.currentData && this.currentData.level == 2 ? '修改成功！' : '保存成功！')
                // 更新规则配置树
                this.getRuleConfigTree()
                // 关闭弹窗，重置数据
				    		this.ruleDialogClose()
				    	}
				    }).catch(err => {
				    	this.$store.dispatch('loading/CHANGE_LOADING',false);
				    });
          }
        })
      },

      // ---保存新版本
      // 弹窗关闭
      versionDialogClose(){
        this.versionForm = {
          versionName: '',
          versionCode: '',
          remark: ''
        }
        this.versionVisible = false
      },
      // 点击保存按钮
      versionSaveClick(){
        this.$refs.versionForm.validate((valid) => {
          if (valid) {
            let url = this.ruleType == '1' ? saveNewPhysicalRiskRuleApi : this.ruleType == '2' ? saveNewHealthRiskRuleApi : 
                this.ruleType == '3' ? saveNewSpecialScoreRuleApi : saveNewUnderwritingEvaluationRuleApi
            let msg = `存在数据为空的${this.ruleGroupDic.filter(fItem=>fItem.value == this.ruleType)[0].label}`
            let refName = this.ruleType == '1' ? 'physicalRiskRule' : this.ruleType == '2' ? 'healthRiskRule' : this.ruleType == '3' ? 'specialScoreRule' : 'underwriteEvaluationRule'
            let ruleObj = this.$refs[refName].saveHandle()
            console.log(ruleObj,'ruleObj');
            if(!ruleObj.flag){
              this.$message.warning(ruleObj.msg ? ruleObj.msg : msg)
              return
            }
            let params = {
              diseaseRuleId: this.diseaseRuleId,
              versionCode: this.versionForm.versionCode,
              versionName: this.versionForm.versionName,
              diseaseName: this.diseaseName,
              ruleName: this.ruleGroupDic.filter(item=>item.value == this.ruleType)[0].label,
              remark: this.versionForm.remark,
              ruleList: ruleObj.filterArr
            }
            this.saveLoading = true
            url(params).then(res => {
              this.saveLoading = false
				    	if (res.resultCode == constant.SUCCESS) {
                this.$message.success('保存成功')
                setTimeout(()=>{
                  // 关闭弹窗，重置数据
				    		  this.versionDialogClose()
                  // 更新当前覆盖后的版本数据
                  this.getRuleTypeList()
                },500) 
				    	}
				    }).catch(err => {
				    	this.saveLoading = false
				    });
          }
        })
      },

      // ---点击按钮组触发
      // 点击覆盖原版本时触发
      coverVersion(){
        this.$confirm('是否覆盖原版本?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let url = this.ruleType == '1' ? savePhysicalRiskRuleApi : this.ruleType == '2' ? saveHealthRiskRuleApi : 
                this.ruleType == '3' ? saveSpecialScoreRuleApi : saveUnderwritingEvaluationRuleApi
          let msg = `存在数据为空的${this.ruleGroupDic.filter(fItem=>fItem.value == this.ruleType)[0].label}`
          let refName = this.ruleType == '1' ? 'physicalRiskRule' : this.ruleType == '2' ? 'healthRiskRule' : this.ruleType == '3' ? 'specialScoreRule' : 'underwriteEvaluationRule'
          let ruleObj = this.$refs[refName].saveHandle()
          console.log(ruleObj,'ruleObj');
          if(!ruleObj.flag){
            this.$message.warning(ruleObj.msg ? ruleObj.msg : msg)
            return
          }
          let params = {
            diseaseRuleId: this.diseaseRuleId,
            diseaseName: this.diseaseName,
            ruleName: this.ruleGroupDic.filter(item=>item.value == this.ruleType)[0].label,
            // versionCode: this.versionId,
            ruleList: ruleObj.filterArr
          }
          this.coverLoading = true
          url(params).then(res => {
            this.coverLoading = false
			  		if (res.resultCode == constant.SUCCESS) {
              this.$message.success('保存成功')
              setTimeout(()=>{
                // 更新当前覆盖后的版本数据
                this.getRuleTypeList(this.diseaseRuleId,this.versionId)
              },500)
			  		}
				  }).catch(err => {
			  		this.coverLoading = false;
				  });
        }).catch(() => {});
      },
      // 点击保存新版本按钮触发
      addNewVersion(){
        this.versionVisible = true
      },
      // 导出execl
      importExcel(){
        let url = this.ruleType == '1' ? importPhysicalRiskRuleApi : this.ruleType == '2' ? importHealthRiskRuleApi :
         this.ruleType == '3' ? importSpecialScoreRuleApi : importUnderwritingEvaluationRuleApi
        this.importLoading = true

        url({diseaseRuleId: this.diseaseRuleId,versionCode: this.versionId}).then(res => {
          this.importLoading = false
          let disposition = res.headers['content-disposition'],
          filename = decodeURI(disposition.split(';')[1].split('=')[1]).replace(/^(\s|")+|(\s|")+$/g, '')
          filename = filename.split('+-+')[1]
          let blob = new Blob([res.data], { type: `${res.data.type};charset=utf-8`})
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, filename);
          }
          let downloadElement = document.createElement('a');
          let href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.href = href;
          downloadElement.download = filename; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
        }).catch(err => {
          this.importLoading = false
        });
      },
      // 点击查看版本按钮触发
      viewVersion(){
        this.viewVisible = true
        setTimeout(()=>{
          this.$refs.versionView.getDataList()
        })
      },
      // 查看指定版本
      specifiedVersion(diseaseRuleId,version){
        this.getRuleTypeList(diseaseRuleId,version)
        this.viewVisible = false
      }
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      },
      visible(value) {
        if (value) {
          document.body.addEventListener('click', this.closeMenu)
        } else {
          document.body.removeEventListener('click', this.closeMenu)
        }
      }
    },
  }
</script>

<style lang="less" scoped>
.fillcontain {
  padding-bottom: 0;
  .fastQuery {
    padding: 15px 20px 10px 20px;
    background: #fff;
    border-bottom: 1px solid #e1e1e1;
    .fastQuery-title {
      font-size: 16px;
    }
  }
  .content{
    padding-top: 15px;
    /* height: calc(100vh - 262px);
    min-height: 450px; */
    height: 570px;
    margin: 0 10px;
    padding-bottom: 10px;
    display: flex;
  }
  .left-tree{
    width: 300px;
    margin-right: 10px;
    border: 1px solid #e1e1e1;
    .tree-filter{
      padding: 20px 20px 0 20px;
    }
    .tree-content{ 
      margin: 0 10px;
    }
    .expanded{
      font-size: 12px;
      border: 1px solid #808080;
      color: #808080;
    }
    .node-label{
      display: inline-block;
      padding: 10px 0;
      width: 200px;
    }
    .node-active{
      color: #83a1f7;
    }
    .node-ellips{
      margin-left: 14px;
      display: inline-block;
      max-width: 152px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .custom-tree-node{
      display: flex;
      align-items: center;
      flex: 1;
    }
  }
  .right-main{
    flex: 1;
    overflow: auto;
    .btn-list{
      position: relative;
      background: #f8f8f8;
      padding: 10px 0;
      margin-bottom: 10px;
      p{
        position: absolute;
        right: 10px;
        top: 16px;
        color: #f76767;
      }
    }
  }
}

.contextMenu{
  margin: 0;
  border: 1px solid #dadce0;
  background: #fff;
  z-index: 3000;
  position: fixed;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgb(0 0 0 / 30%);
  text-align: center;
  width: 120px;
}
.contextMenu li{
  cursor: pointer;
  margin:8px;
}
.contextMenu li:hover{
  color: #68a3fc;
}
/deep/ .pb15{
  padding: 0px !important;
}

/deep/ .el-tree{
  background: #fff !important;
  height: calc(100% - 100px);
  overflow: auto;
  margin-top: 20px !important;
  padding-top: 0px;
}
/deep/ .el-tree-node__expand-icon{
  display: none;
}
/deep/ .el-tree-node__content{
  height: 30px;
}
/deep/ .el-tree-node{
  position: relative;
}
/deep/ .left-tree .tree-content > .el-tree-node:before,
/deep/ .left-tree .tree-content > .el-tree-node > .el-tree-node__children > .el-tree-node:before,
/deep/ .left-tree .tree-content > .el-tree-node > .el-tree-node__children > .el-tree-node .el-tree-node__children:before {
  content: " ";
  border-left: 1px dashed #4386c6;
  position: absolute;
  bottom: 0px;
  top: 30px;
  left: 8px;
  width: 1px;
  z-index: 98;
}
/deep/ .left-tree .tree-content > .el-tree-node > .el-tree-node__children > .el-tree-node:before{
  left: 24px;
}
/deep/ .left-tree .tree-content > .el-tree-node > .el-tree-node__children > .el-tree-node .el-tree-node__children:before{
  left: 45px;
  top: 45px;
  height: calc(100% - 60px);
}
/* /deep/ .el-icon-delete{
  position: absolute;
  right: 0px;
} */
</style>